package info.niwota.profile;

import info.niwota.webapp.WebIntents;

import org.json.JSONObject;

import android.app.ListActivity;
import android.content.Intent;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

public class PeerListActivity extends ListActivity {

	private static final String TAG = "PeerListActivity";

	protected PeerListAdapter adapter;

	public PeerListActivity() {
		super();
	}

	protected void updateUi() {

		getListView().setAdapter(adapter);
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			doBack();
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	private void doBack() {
		finish();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (Debug.DEBUG) {
			Log.d(TAG, "onActivityResult requestCode: " + requestCode
					+ " resultCode: " + resultCode + " data: " + data);
		}
	}

	public void onClick(View v) {
		// int id = v.getId();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		//
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo cmi = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();
		if (cmi == null) {
			return true;
		}
		int pos = cmi.position;
		JSONObject ri = (JSONObject) adapter.getItem(pos);
		if (ri == null) {
			return true;
		}
		switch (item.getItemId()) {
		default:
		}
		return true;
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onListItemClick(ListView list, View view, int pos, long id) {
		if (adapter == null) {
			return;
		}
		JSONObject ri = (JSONObject) adapter.getItem(pos);
		if (ri != null) {
			doShowPeerProfile(ri);
		}
	}

	private void doShowPeerProfile(JSONObject item) {
		try {
			String peer = item.getString("peer");
			Intent i = new Intent(this, ViewProfileActivity.class);
			i.putExtra(WebIntents.EXTRA_PEER, peer);

			startActivity(i);
		} catch (Exception e) {
			Toast.makeText(this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
		}
	}
}